﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Mail;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using D.Net.EmailInterfaces;
using D.Net.EmailClient;

namespace FmtxMail
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        const string rn = "\r\n";
        NetworkStream _nstream;
        StreamReader _streamread;
        TcpClient client;
        IEmailClient iec = EmailClientFactory.GetClient(EmailClientEnum.IMAP);
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            
            try
            {
                iec.Connect(txtimap.Text, txtuname.Text, txtpwd.Password, 143, false);
                if (iec.IsConnected)
                {
                    rtxtconn.AppendText("登录成功！"+rn);
                }
                else {
                    rtxtconn.AppendText("登录失败！"+rn);
                }
                iec.SetCurrentFolder("INBOX");//drafts草稿/junk垃圾箱/sent Messages发送信息（应该是发件箱吧）
                iec.LoadMessages();
                rtxtconn.AppendText("一共"+iec.Messages.Count+"封邮件！"+rn);
                for (int i = 0; i < iec.Messages.Count; i++)
                {
                    IEmail iemail = iec.Messages[i];
                    iemail.LoadInfos();
                    rtxtconn.AppendText("编号："+i+"   Subject:" + iemail.Subject + rn);
                }
                
            }
            catch (Exception ex)
            {
                rtxtmailbody.AppendText(ex.Message);
            }

            //client = new TcpClient("imap.qq.com", 143);
            //_nstream=client.GetStream();
            //_streamread = new StreamReader(client.GetStream());
            ////var res = _streamread.ReadLine();
            ////rtxtconn.AppendText(res+rn);
            //rtxtconn.AppendText(Request(""));
            //var login = "C1 LOGIN " + txtuname.Text + " \"" + txtpwd.Password+"\"" + rn;
            //var logres = Request(login);
            //if (logres.IndexOf("ok") != -1)
            //{
            //    rtxtconn.AppendText(logres);
            //    rtxtconn.AppendText(Request("C2 LIST \"\" *" + rn));
            //    rtxtconn.AppendText(Request("C3 SELECT \"INBOX\"" + rn));
            //    rtxtconn.AppendText(Request("C4 STATUS INBOX (MESSAGES)" + rn));
            //}
            //else {
            //    rtxtconn.AppendText("登录失败！");
            //}
            //var buffer = Encoding.ASCII.GetBytes(login);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res+rn);
            //var data = "C2 CAPABILITY" + rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer,0,buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res+rn);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);


            //data = "C3 LIST \"\" *" + rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);
            //res = _streamread.ReadToEnd();
            //rtxtconn.AppendText(res + rn);

            //data = "C4 LSUB \"\" *" + rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);
            //res = _streamread.ReadToEnd();
            //rtxtconn.AppendText(res + rn);

            //data = "C4 SELECT \"Junk\"" + rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);
            //res = _streamread.ReadToEnd();
            //rtxtconn.AppendText(res + rn);

            //data = "FETCH 7 body[header]" + rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);
            //res = _streamread.ReadToEnd();
            //rtxtconn.AppendText(res + rn);


            //data = "C4 SELECT \"INBOX\"" + rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadToEnd();
            //rtxtconn.AppendText(res + rn);
            //Thread.Sleep(10000);
            //data = "C5 LSUB \"\"*"+rn;
            //rtxtconn.AppendText(data + "=");
            //buffer = Encoding.ASCII.GetBytes(data);
            //_nstream.Write(buffer, 0, buffer.Length);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);
            //res = _streamread.ReadLine();
            //rtxtconn.AppendText(res + rn);

        }

        private string Request(string cmd)
        {
            try
            {
                if (client != null && client.Connected)
                {
                    byte[] data = Encoding.ASCII.GetBytes(cmd);
                    _nstream.Write(data, 0, data.Length);

                    string res="";
                    do
                    {
                        byte[] buffer = new byte[1024];
                        _nstream.Read(buffer, 0, buffer.Length);
                        res += Encoding.ASCII.GetString(buffer);
                    } while (res.IndexOf('\0')==-1);
                    res = res.Substring(0, res.IndexOf('\0'));
                    _nstream.Flush();
                    return res;
                }
                else
                {
                    return "服务器已断开！";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string RequestBody(string cmd)
        {
            try
            {
                if (client != null && client.Connected)
                {
                    byte[] data = Encoding.ASCII.GetBytes(cmd);
                    _nstream.Write(data, 0, data.Length);

                    string res = _streamread.ReadToEnd();
                    //do
                    //{
                    //    byte[] buffer = new byte[1024];
                    //    _nstream.Read(buffer, 0, buffer.Length);
                    //    res += Encoding.ASCII.GetString(buffer);
                    //} while (res.IndexOf('\0') == -1);
                    //res = res.Substring(0, res.IndexOf('\0'));
                    _nstream.Flush();
                    return res;
                }
                else
                {
                    return "服务器已断开！";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        private void btngetmail_Click(object sender, RoutedEventArgs e)
        {
            rtxtmailbody.Document.Blocks.Clear();
            var num = txtmailnum.Text;
            IEmail iemail = iec.Messages[Convert.ToInt32(num)];
            iemail.LoadInfos();
            rtxtmailbody.AppendText("From:" + iemail.From[0] + rn + rn);
            rtxtmailbody.AppendText("附件数:" + iemail.Attachments.Count + rn + rn);
            rtxtmailbody.AppendText("Date:" + iemail.Date.ToString() + rn);
            rtxtmailbody.AppendText("Subject:" + iemail.Subject + rn);
            rtxtmailbody.AppendText("SequenceNumber:" + iemail.SequenceNumber.ToString() + rn);
            rtxtmailbody.AppendText("TextBody:" + iemail.TextBody + rn);
  

            //rtxtmailbody.AppendText(RequestBody("C1 FETCH " + num + " body[header]" + rn));
            //rtxtmailbody.AppendText(Request(""));
            //rtxtmailbody.AppendText(RequestBody("C2 FETCH " + num + " body[text]" + rn));
        }

        private void btnloginout_Click(object sender, RoutedEventArgs e)
        {
            
            //rtxtconn.AppendText(Request("C1 LOGOUT" + rn));
            //_nstream.Close();
            //_nstream.Dispose();
        }
    }
}
